// 主游戏逻辑
import { 
    gameState,
    saveGameData,
    resetGameData,
    ingredientsData
} from './data.js';
import { getActiveCharacter, characterManager } from './character.js';
import { showAlert } from './utils.js';

import { 
    cityManager, 
    initCityPanel, 
    updateCityInfoDisplay,
    startBuilding,
    updateBuildingsList
} from './city.js';

import { 
    initFarmingPanel, 
    updateFarmInfoDisplay,
    plantCrop,
    harvestCrop,
    updateFarmStatus
} from './farming.js';
import { cookingManager, getEffectName } from './cooking.js';

import { 
    initSkillsPanel, 
    updateSkillsList 
} from './skillUI.js';

// 游戏初始化
function initGame() {
    // 初始化管理器
    resetGameData();
    
    // 初始化各个面板
    initPlayerPanel();
    initCityPanel();
    initFarmingPanel();
    // 烹饪面板
    initInventoryPanel();
    initSkillsPanel();
    
    // 添加所有表格UI样式
    addInventoryStyles();
    addBuildingsListStyles();
    addFarmStatusStyles();
    
    // 更新游戏时间显示
    updateGameTimeDisplay();
    
    // 绑定全局函数，使HTML中的onclick事件可以调用
    window.showPanel = showPanel;
    window.nextDay = nextDay;
    window.saveGame = saveGame;
    window.startBuilding = startBuilding;
    window.plantCrop = plantCrop;
    window.harvestCrop = harvestCrop;
}

// 初始化角色面板
function initPlayerPanel() {
    updatePlayerStats();
}

// 更新玩家状态显示
function updatePlayerStats() {
    const activeCharacter = getActiveCharacter();
    document.getElementById('happiness').textContent = Math.round(activeCharacter.happiness);
    document.getElementById('stamina').textContent = Math.round(activeCharacter.stamina);
    document.getElementById('health').textContent = Math.round(activeCharacter.health);
    document.getElementById('strength').textContent = activeCharacter.strength;
    document.getElementById('agility').textContent = activeCharacter.agility;
    document.getElementById('intelligence').textContent = activeCharacter.intelligence;
    document.getElementById('charisma').textContent = activeCharacter.charisma;
}

// 初始化物品面板
function initInventoryPanel() {
    updateInventoryDisplay();
}

// 更新物品栏显示
function updateInventoryDisplay() {
    const inventoryList = document.getElementById('inventoryList');
    inventoryList.innerHTML = '';
    
    // 显示物品
    const itemsDiv = document.createElement('div');
    itemsDiv.className = 'items-section';
    itemsDiv.innerHTML = '<h4>物品</h4>';
    
    const activeCharacter = getActiveCharacter();
    if (activeCharacter.inventory.length === 0) {
        itemsDiv.innerHTML += '<p>物品栏为空</p>';
    } else {
        const itemsTable = document.createElement('table');
        itemsTable.innerHTML = `
            <thead>
                <tr>
                    <th>物品名称</th>
                    <th>数量</th>
                    <th>描述</th>
                </tr>
            </thead>
            <tbody>
            </tbody>
        `;
        
        const itemsTbody = itemsTable.querySelector('tbody');
        activeCharacter.inventory.forEach(item => {
            
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${item.name}</td>
                <td>${item.quantity}</td>
                <td>${item.description}</td>
            `;
            itemsTbody.appendChild(row);
        });
        
        itemsDiv.appendChild(itemsTable);
    }
    
    inventoryList.appendChild(itemsDiv);
}

// 获取资源显示名称
function getResourceDisplayName(resourceKey) {
    const names = {
        money: '金钱',
        wood: '木材',
        stone: '石头',
        metal: '金属'
    };
    return names[resourceKey] || resourceKey;
}

// 添加物品面板样式
function addInventoryStyles() {
    const style = document.createElement('style');
    style.textContent = `
        .resources-section,
        .items-section {
            background-color: #fff;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 20px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }
        
        .resources-section h4,
        .items-section h4 {
            color: #8b4513;
            margin-bottom: 10px;
            border-bottom: 1px solid #cd853f;
            padding-bottom: 5px;
        }
        
        .resources-section table,
        .items-section table {
            width: 100%;
            border-collapse: collapse;
        }
        
        .resources-section th,
        .items-section th {
            background-color: #f0e6d2;
            padding: 8px;
            text-align: left;
            border-bottom: 2px solid #cd853f;
        }
        
        .resources-section td,
        .items-section td {
            padding: 8px;
            border-bottom: 1px solid #f0e6d2;
        }
        
        .resources-section tr:hover,
        .items-section tr:hover {
            background-color: #fff8e7;
        }
    `;
    document.head.appendChild(style);
}

// 添加建筑列表样式
function addBuildingsListStyles() {
    const style = document.createElement('style');
    style.textContent = `
        #buildingsList {
            background-color: #fff;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 20px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }
        
        .buildings-table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 10px;
        }
        
        .buildings-table th {
            background-color: #f0e6d2;
            padding: 8px;
            text-align: left;
            border-bottom: 2px solid #cd853f;
            color: #8b4513;
        }
        
        .buildings-table td {
            padding: 8px;
            border-bottom: 1px solid #f0e6d2;
        }
        
        .buildings-table tr:hover {
            background-color: #fff8e7;
        }
        
        #buildingsList p {
            margin-top: 10px;
            color: #8b4513;
            font-style: italic;
        }
    `;
    document.head.appendChild(style);
}

// 添加农田状态列表样式
function addFarmStatusStyles() {
    const style = document.createElement('style');
    style.textContent = `
        #farmStatus {
            background-color: #fff;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 20px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }
        
        #farmStatus table {
            width: 100%;
            border-collapse: collapse;
        }
        
        #farmStatus table th {
            background-color: #f0e6d2;
            padding: 8px;
            text-align: left;
            border-bottom: 2px solid #cd853f;
            color: #8b4513;
        }
        
        #farmStatus table td {
            padding: 8px;
            border-bottom: 1px solid #f0e6d2;
        }
        
        #farmStatus table tr:hover {
            background-color: #fff8e7;
        }
        
        #farmStatus p {
            color: #8b4513;
            font-style: italic;
        }
        
        .farm-info {
            background-color: #fff;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 20px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }
        
        .info-item {
            margin-bottom: 10px;
        }
        
        .info-item label {
            font-weight: bold;
            color: #8b4513;
            margin-right: 10px;
        }
    `;
    document.head.appendChild(style);
}

// 显示指定面板
function showPanel(panelId) {
    // 隐藏所有面板
    const panels = document.querySelectorAll('.panel');
    panels.forEach(panel => {
        panel.style.display = 'none';
    });
    
    // 显示选中的面板
    const selectedPanel = document.getElementById(panelId);
    if (selectedPanel) {
        selectedPanel.style.display = 'block';
    }
    
    // 根据显示的面板更新内容
    if (panelId === 'playerPanel') {
        updatePlayerStats();
    } else if (panelId === 'cityPanel') {
        updateCityInfoDisplay();
        updateBuildingsList();
    } else if (panelId === 'farmingPanel') {
        updateFarmInfoDisplay();
        updateFarmStatus();
    } else if (panelId === 'inventoryPanel') {
        updateInventoryDisplay();
    } else if (panelId === 'skillsPanel') {
        updateSkillsList();
    } else if (panelId === 'cookingPanel') {
        updateCookingUI();
    }
}

// 推进到下一天
function nextDay() {
    // 更新游戏日期
    updateGameDate();
    // 更新游戏时间显示
    updateGameTimeDisplay();
    // 通过城市管理器更新所有城市的天气、温度
    cityManager.updateAllCities();
    // 更新玩家状态
    updateDailyPlayerStats();
    
    // 自动保存（每隔几天）
    if (gameState.day % gameState.autoSaveInterval === 0) {
        const citiesData = cityManager.getAllCities();
        saveGameData(citiesData);
    }
    
    // 更新所有显示
    updateCityInfoDisplay();
    updateFarmInfoDisplay();
    updatePlayerStats();
}

// 更新游戏日期
function updateGameDate() {
    gameState.day += 1;
    
    // 检查是否需要换季节
    if (gameState.day > gameState.currentSeasonTotalDays) {
        gameState.day = 1;
        nextSeason();
    }
}

// 进入下一个季节
function nextSeason() {
    const seasons = ['春季', '夏季', '秋季', '冬季'];
    const currentSeasonIndex = seasons.indexOf(gameState.season);
    const nextSeasonIndex = (currentSeasonIndex + 1) % seasons.length;
    gameState.season = seasons[nextSeasonIndex];
    
    // 更新当前季节的总天数
    gameState.currentSeasonTotalDays = gameState.seasonDays[gameState.season];
    
    // 如果从冬季进入春季，年份+1
    if (gameState.season === '春季') {
        gameState.year += 1;
    }
    
    // 季节变化时的特殊处理
    handleSeasonChange();
}

// 处理季节变化
function handleSeasonChange() {
    // 根据季节调整所有角色状态
    characterManager.adjustAllCharactersForSeason(gameState.season);
}

// 更新每日玩家状态
function updateDailyPlayerStats() {
    // 更新所有角色的每日状态
    characterManager.updateAllCharactersDailyStats();
}

// 更新游戏时间显示
function updateGameTimeDisplay() {
    document.getElementById('year').textContent = `第${gameState.year}年`;
    document.getElementById('season').textContent = gameState.season;
    document.getElementById('day').textContent = `第${gameState.day}天`;
}

// 保存游戏
function saveGame() {
    // 获取所有城市数据
    const citiesData = cityManager.getAllCities();
    const success = saveGameData(citiesData);
    if (success) {
        alert('游戏保存成功！');
    } else {
        alert('游戏保存失败，请稍后再试。');
    }
}


// 当页面加载完成后初始化游戏
document.addEventListener('DOMContentLoaded', initGame);

// 为了在HTML中直接调用函数
window.cookRecipe = function(recipeId) {
    const character = getActiveCharacter();
    const result = cookingManager.cookRecipe(character, recipeId);
    
    if (result.success) {
            // 更新UI
            updateCookingUI();
            updateInventoryDisplay();
            alert(result.message);
        
        // 检查是否有升级消息
        const levelUpResult = character.checkSkillLevelUp('加工');
        if (levelUpResult.leveledUp) {
                alert(levelUpResult.message);
            }
    } else {
        alert(result.message);
    }
};

window.useIngredient = function(itemId) {
    const character = getActiveCharacter();
    const result = cookingManager.useIngredient(character, itemId);
    
    if (result.success) {
            // 更新UI
            updateCookingUI();
            updateInventoryDisplay();
            updatePlayerStats();
            alert(result.message);
        } else {
            alert(result.message);
        }
};

// 更新烹饪UI界面
function updateCookingUI() {
    updateRecipesList();
    updateCookingMaterials();
}

// 更新食谱列表显示
function updateRecipesList() {
    const recipesContainer = document.getElementById('recipesList');
    if (!recipesContainer) return;
    
    recipesContainer.innerHTML = '';
    
    const character = getActiveCharacter();
    const availableRecipes = cookingManager.getAvailableRecipes(character);
    
    availableRecipes.forEach(recipe => {
        const recipeElement = document.createElement('div');
        recipeElement.className = 'recipe-item';
        
        recipeElement.innerHTML = `
            <h4>${recipe.name}</h4>
            <p>${recipe.description}</p>
            <div class="recipe-effects">
                <span>效果: </span>
                ${Object.entries(recipe.effects).map(([effect, value]) => 
                    `<span>${getEffectName(effect)}+${value}</span>`
                ).join(', ')}
            </div>
            <div class="recipe-ingredients">
                <span>材料: </span>
                ${Object.entries(recipe.ingredients).map(([ingredientId, amount]) => {
                    const ingredient = ingredientsData[ingredientId];
                    return ingredient ? `<span>${ingredient.name} x${amount}</span>` : `<span>未知材料 x${amount}</span>`;
                }).filter(Boolean).join(', ')}
            </div>
            <button onclick="cookRecipe('${recipe.id}')" ${!recipe.canCook ? 'disabled' : ''}>
                ${recipe.canCook ? '烹饪' : '材料不足'}
            </button>
        `;
        
        recipesContainer.appendChild(recipeElement);
    });
}

// 更新烹饪材料显示
function updateCookingMaterials() {
    const materialsContainer = document.getElementById('cookingMaterials');
    if (!materialsContainer) return;
    
    materialsContainer.innerHTML = '<h4>可用材料</h4>';
    
    const character = getActiveCharacter();
    const availableMaterials = cookingManager.getAvailableMaterials(character);
    
    if (availableMaterials.length === 0) {
        materialsContainer.innerHTML += '<p>暂无可用材料</p>';
        return;
    }
    
    availableMaterials.forEach(material => {
        const materialElement = document.createElement('div');
        materialElement.className = 'material-item';
        materialElement.innerHTML = `
            <span>${material.name}: ${material.quantity}</span>
            ${material.effects ? 
                `<button onclick="useIngredient('${material.id}')">直接使用</button>` : ''}
        `;
        materialsContainer.appendChild(materialElement);
    });
}